package com.itbaizhan.seckill.service.impl;

import com.itbaizhan.common.vo.DetailsVo;
import com.itbaizhan.common.vo.LivegoodsResult;
import com.itbaizhan.details.service.DetailsService;
import com.itbaizhan.order.service.OrderService;
import com.itbaizhan.pojo.Order;
import com.itbaizhan.seckill.mapper.RabbitmqSeckillMapper;
import com.itbaizhan.seckill.service.RabbitmqSeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@DubboService
public class RabbitmqSeckillServiceImpl implements RabbitmqSeckillService {
    //远程服务调用
    @DubboReference
    private DetailsService detailsService;
    @Autowired
    private RabbitmqSeckillMapper rabbitmqSeckillMapper;
    @RabbitListener(queues = "livegoods.queue.seckill")
    @Override
    public Boolean seckill(Long houseId) {
        LivegoodsResult result = detailsService.showDetails(houseId);
        DetailsVo detailsVo =(DetailsVo) result.getData();
        if(detailsVo.getBuy()){ //已经被预定了
            return false;
        }
        //查询数据库
        Boolean buy = rabbitmqSeckillMapper.selectBuyById(houseId);
        if(buy){ //已经被预定
            //更新缓存
            detailsService.clearHouseCache(houseId);
            detailsService.showDetails(houseId);
            return false;
        }
        // 预定
        int index = rabbitmqSeckillMapper.updateBuyById(houseId);
        if(index==1){ //预定成功
            detailsService.clearHouseCache(houseId);
            detailsService.showDetails(houseId);
            return true;
        }
        return false;
    }

    @DubboReference
    private OrderService orderService;

    @RabbitListener(queues = "livegoods.queue.order")
    @Override
    public void create(Map<String, Object> param) {
        Order order = new Order();
        Long id = (Long) param.get("id");
        String phone = param.get("phone").toString();
        order.setId(id);
        order.setUserPhone(phone);

        LivegoodsResult result = detailsService.showDetails(id);
        DetailsVo detailsVo =(DetailsVo) result.getData();

        order.setImg(detailsVo.getImgs()[0]);
        order.setPrice(detailsVo.getPrice());
        order.setHouseTitle(detailsVo.getTitle());
        order.setCommentState(0);
        order.setHouseType(detailsVo.getHouseType());
        order.setRentType(detailsVo.getRentType());
        order.setHouseId(detailsVo.getId());

        orderService.insertOrder(order);
    }
}
